import {
  baseUrl,
  baseUrlTow,
  baseUrlThree
} from './config.js'

/**
 * url 请求地址
 * data 请求参数
 * isApi 判断使用哪一个api
 * loading 可选项 是否需要loading,默认为true
 */
const get = (url, data, isApi,loading) => {
  let auth
  if (wx.getStorageSync('accessToken')) {
    auth = {
      'Authorization': wx.getStorageSync('accessToken')
    }
  }


  switch (isApi) {
    case 1:
      url = baseUrl + url;
      break;
    case 2:
      url = baseUrlTow + url;
      break;
    case 3:
      url = baseUrlThree + url;
      break;
  }
  
  return new Promise((resolve, reject) => {
    if (loading) {
      wx.showLoading({
        title: '玩命加载中。。。。',
      })
    }
    wx.request({
      url,
      method: 'get',
      data,
      header: auth,
      success: (res) => {
        if (res.data.code === 0) {
          resolve(res.data);
        } else if (res.data.code === 61) {
          resolve(res.data);
          wx.redirectTo({
            url: '/pages/login/login'
          })
        }else {
          resolve(res.data);
        }
      },
      fail: (err) => {
        // 弹窗轻提示用户错误的信息
        console.log('请求失败信息', err);
      },
      complete: () => {
        if (loading) {
          wx.hideLoading()
        }
      }
    })
  })
}

const post = (url, data, isApi,loading) => {
  let auth
  if (wx.getStorageSync('accessToken')) {
    auth = {
      'Authorization': wx.getStorageSync('accessToken')
    }
  }

  switch (isApi) {
    case 1:
      url = baseUrl + url;
      break;
    case 2:
      url = baseUrlTow + url;
      break;
    case 3:
      url = baseUrlThree + url;
      break;
  }

  return new Promise((resolve, reject) => {
    if (loading) {
      wx.showLoading({
        title: '加载中...',
      })
    }
    wx.request({
      url,
      method: 'post',
      data,
      header: auth,
      success: (res) => {
        if (res.data.code === 0) {
          resolve(res.data);
        } else if (res.data.code === 61) {
          resolve(res.data);
          console.log(res.data, "res.data/post");
          wx.redirectTo({
            url: '/pages/login/login'
          })
        } else {
          resolve(res.data);
        }
      },
      fail: (err) => {
        console.log('请求失败信息', err);
      },
      complete: () => {
        let s = setTimeout(function () {
          wx.hideLoading();
          clearTimeout(s)
        }, 1000)
      }
    })
  })
}

export default {
  get,
  post
}